package com.molichuxing.services.infrastructure.service.impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.services.infrastructure.bean.EnterpriseCarBean;
import com.molichuxing.services.infrastructure.convertor.Convert;
import com.molichuxing.services.infrastructure.dao.EnterpriseCarMapper;
import com.molichuxing.services.infrastructure.dto.request.create.EnterpriseCarCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.EnterpriseCarModifyDto;
import com.molichuxing.services.infrastructure.dto.response.EnterpriseCarDto;
import com.molichuxing.services.infrastructure.service.EnterpriseCarService;
import com.molichuxing.services.property.EnterpriseCarStateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 企业订单车辆
 *
 * @Author zoumingyu
 * @Date 2020年06月04日
 */
@Service("enterpriseCarService")
public class EnterpriseCarServiceImpl implements EnterpriseCarService {
    private static final Logger logger = LoggerFactory.getLogger(EnterpriseCarServiceImpl.class);

    @Resource
    private EnterpriseCarMapper enterpriseCarMapper;

    /**
     * 获取企业订单车辆信息
     *
     * @param orderCode 订单号
     * @return List
     */
    @Override
    public List<EnterpriseCarDto> getEnterpriseCar(Long orderCode) {
        return Convert.toEnterpriseCarDto(enterpriseCarMapper.getByOrderCode(orderCode, null));
    }

    /**
     * 获取企业订单车辆信息
     *
     * @param orderCode 订单号
     * @param carState  企业订单车辆状态
     * @return List
     */
    @Override
    public List<EnterpriseCarDto> getEnterpriseCar(Long orderCode, EnterpriseCarStateEnum carState) {
        return Convert.toEnterpriseCarDto(enterpriseCarMapper.getByOrderCode(orderCode, carState == null ? null : carState.getValue()));
    }

    /**
     * 获取企业订单车辆信息
     *
     * @param orderCode 订单号
     * @param carId     车辆id
     * @return EnterpriseCarDto
     */
    @Override
    public EnterpriseCarDto getEnterpriseCar(Long orderCode, Integer carId) {
        return Convert.toEnterpriseCarDto(enterpriseCarMapper.getByOrderCodeAndCarId(orderCode, carId));

    }

    /**
     * 批量新增订单车辆信息
     *
     * @param createDtoList 新增信息
     * @return boolean
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public boolean createBatch(List<EnterpriseCarCreateDto> createDtoList) {
        List<EnterpriseCarBean> createBeanList = Convert.toEnterpriseCarBean(createDtoList);
        return createBeanList != null && (enterpriseCarMapper.createBatch(createBeanList) > 0);
    }

    /**
     * 修改订单车辆状态
     *
     * @param orderCode 订单号
     * @param oldState  旧状态
     * @param newState  新状态
     * @return boolean
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public boolean modifyState(Long orderCode, EnterpriseCarStateEnum oldState, EnterpriseCarStateEnum newState) {
        return enterpriseCarMapper.modifyState(orderCode, oldState.getValue(), newState.getValue()) > 0;
    }

    /**
     * 修改订单车辆信息-交车
     *
     * @param modifyDto 修改信息
     * @return boolean
     */
    @Override
    public boolean modifyDelivery(EnterpriseCarModifyDto modifyDto) {
        if (modifyDto.getStartMileage() == null) {
            logger.error("订单车辆交车时，起租里程不能为空");
            return false;
        }
        EnterpriseCarBean modifyBean = Convert.toEnterpriseCarBean(modifyDto, EnterpriseCarStateEnum.UNHIRE);
        // 交车，结束里程为空
        modifyBean.setEndMileage(null);
        return enterpriseCarMapper.modifyHandover(modifyBean, EnterpriseCarStateEnum.UNDELIVERY.getValue()) > 0;
    }

    /**
     * 修改订单车辆信息-还车（退租）
     *
     * @param modifyDto 修改信息
     * @return boolean
     */
    @Override
    public boolean modifyReturn(EnterpriseCarModifyDto modifyDto) {
        if (modifyDto.getEndMileage() == null) {
            logger.error("订单车辆还车（退租）时，结束里程不能为空");
            return false;
        }

        EnterpriseCarBean modifyBean = Convert.toEnterpriseCarBean(modifyDto, EnterpriseCarStateEnum.RETURNED);
        // 还车（退租）开始里程为空
        modifyBean.setStartMileage(null);
        return enterpriseCarMapper.modifyHandover(modifyBean, EnterpriseCarStateEnum.LEASE.getValue()) > 0;
    }

    /**
     * 修改订单车辆信息-过户
     *
     * @param modifyDto 修改信息
     * @return boolean
     */
    @Override
    public boolean modifyTransfer(EnterpriseCarModifyDto modifyDto) {
        if (modifyDto.getEndMileage() == null) {
            logger.error("订单车辆过户时，结束里程不能为空");
            return false;
        }

        EnterpriseCarBean modifyBean = Convert.toEnterpriseCarBean(modifyDto, EnterpriseCarStateEnum.TRANSFERED);
        // 过户开始里程为空
        modifyBean.setStartMileage(null);
        return enterpriseCarMapper.modifyHandover(modifyBean, EnterpriseCarStateEnum.LEASE.getValue()) > 0;
    }

    /**
     * 修改订单车辆信息-续租订单生效
     *
     * @param modifyDto 修改信息
     * @return boolean
     */
    @Override
    public boolean modifyLease(EnterpriseCarModifyDto modifyDto) {
        if (modifyDto.getStartMileage() == null) {
            logger.error("订单车辆续租订单生效时，开始里程不能为空");
            return false;
        }

        EnterpriseCarBean modifyBean = Convert.toEnterpriseCarBean(modifyDto, EnterpriseCarStateEnum.LEASE);
        // 续租订单生效结束里程为空
        modifyBean.setEndMileage(null);
        return enterpriseCarMapper.modifyHandover(modifyBean, EnterpriseCarStateEnum.UNHIRE.getValue()) > 0;
    }

    /**
     * 修改订单车辆信息-续租生效，主订单到期
     *
     * @param modifyDto 修改信息
     * @return boolean
     */
    @Override
    public boolean modifyExpire(EnterpriseCarModifyDto modifyDto) {
        if (modifyDto.getEndMileage() == null) {
            logger.error("订单车辆续租订单生效时，主订单结束里程不能为空");
            return false;
        }

        EnterpriseCarBean modifyBean = Convert.toEnterpriseCarBean(modifyDto, EnterpriseCarStateEnum.RELETED);
        // 续续租生效，主订单到期开始里程为空
        modifyBean.setStartMileage(null);
        return enterpriseCarMapper.modifyHandover(modifyBean, EnterpriseCarStateEnum.LEASE.getValue()) > 0;
    }

    /**
     * 根据订单号得到 EnterpriseCarDto
     *
     * @param orderCodeList
     * @return List
     */
    @Override
    public List<EnterpriseCarDto> listEnterpriseCar(List<Long> orderCodeList) {
        return Convert.toEnterpriseCarDto(enterpriseCarMapper.listEnterpriseCar(orderCodeList));
    }

    /**
     * 车辆是否锁定
     *
     * @param carId 车辆id
     * @return boolean true:锁定，false：未锁定
     */
    @Override
    public boolean getCarIsLock(Integer carId) {
        return enterpriseCarMapper.getCarIsLock(carId,
                Arrays.asList(EnterpriseCarStateEnum.UNPAID.getValue(),
                        EnterpriseCarStateEnum.UNDELIVERY.getValue(),
                        EnterpriseCarStateEnum.UNHIRE.getValue(),
                        EnterpriseCarStateEnum.LEASE.getValue())) > 0;
    }

    /**
     * 分页获取专属里程订单信息
     *
     * @param params   listType：列表类型-enum <br/>
     *                 orderStatus：订单状态-enum <br/>
     *                 orderCode：订单号-long <br/>
     *                 userIds：用户id-list <br/>
     *                 storeIds：门店id-list <br/>
     *                 orderTimeStart：下单开始时间-LocalDateTime <br/>
     *                 orderTimeEnd：下单结束时间-LocalDateTime
     * @param pageNum  页数
     * @param pageSize 每页条数
     * @return
     * @throws Exception
     */
    @Override
    public Paged<EnterpriseCarDto> getOrderCarList(Map<String, Object> params, int pageNum, int pageSize)
            throws Exception {

        EnterpriseCarStateEnum enterpriseCarStateEnum = null;
        if (params.get("state") != null) {
            enterpriseCarStateEnum = EnterpriseCarStateEnum.getEnum(Integer.parseInt(params.get("state").toString()));
            params.put("state", enterpriseCarStateEnum.getValue());
        }

        // 拼接条件
        //订单号
        params.put("orderCode", ObjectCastUtil.castString(params.get("orderCode")));
        //车牌号
        params.put("licencePlate", ObjectCastUtil.castString(params.get("licencePlate")));
        //车架号
        params.put("vin", ObjectCastUtil.castString(params.get("vin")));
        //过户订单号
        params.put("orderCodes", ObjectCastUtil.castList(params.get("orderCodes")));
//        //退租订单号
//        params.put("returnedOrderCodes", ObjectCastUtil.castList(params.get("returnedOrderCodes")));
//        //企业名称
//        params.put("enterpriseOrderCodes", ObjectCastUtil.castList(params.get("enterpriseOrderCodes")));

        long total = enterpriseCarMapper.getPageCount(params);
        List<EnterpriseCarBean> page = null;
        if (total > 0) {
            page = enterpriseCarMapper.getPage(params, pageNum, pageSize);
        }
        return new Paged<EnterpriseCarDto>(Convert.toOrderEnterpriseCarDto(page), total, pageSize);
    }

    /**
     * 获取数量
     *
     * @param params
     * @return
     */
    @Override
    public Integer getCount(Map<String, Object> params) {
        long total = enterpriseCarMapper.getPageCount(params);
        int res = Integer.parseInt(total + "");
        return res;
    }

    /**
     * 根据车辆id获取订单车辆
     *
     * @param carId
     * @return
     */
    @Override
    public List<EnterpriseCarDto> getOrderCarListByCarId(Integer carId) {
        List<EnterpriseCarBean> list = enterpriseCarMapper.getListByCarId(carId);
        if (list != null && list.size() > 0) {
            return Convert.toOrderEnterpriseCarDto(list);
        }
        return null;
    }

}
